Why use Dynamic Visualization?

Early dynamic graphics in R

Recent emerging frameworks

leaflet

open-source JavaScript library for mobile-friendly interactive maps, designed with simplicity, performance and usability in mind

plotly.js

Built on top of d3.js and stack.gl, plotly.js is a high-level, declarative charting library. plotly.js ships with 20 chart types, including 3D charts, statistical graphs, and SVG maps

bokeh

Python interactive visualization library that targets modern web browsers for presentation. Its goal is to provide elegant, concise construction of novel graphics in the style of d3.js

Vega

A visualization grammar, a declarative language for creating, saving, and sharing interactive visualization designs

Shift to using HTML5 + CSS + javascript

Built on the R package knitr + rmarkdown

knitr is an engine for dynamic report generation with R. It is a package in the statistical programming language R that enables integration of R code into LaTeX, LyX, HTML, Markdown, AsciiDoc, and reStructuredText documents.        –Wikipedia

rmarkdown is an R flavoured extension to the markdown text-to-HTML conversion language

Rationalle

     

New dynamic graphics R packages

  • leaflet - Create and customize interactive maps using the 'Leaflet' JavaScript library and the 'htmlwidgets' package

  • plotly - Easily translate 'ggplot2' graphs to an interactive web-based version and/or create custom web-based visualizations directly from R.

  • rbokeh - A native R plotting library that provides a flexible declarative interface for creating interactive web-based graphics, backed by the Bokeh visualization library

  • shiny - Build interactive web applications with R.

All available on CRAN and GitHub

Graphics rendered in RStudio Viewer, Rmarkdown documents, and as web browser content

Interactive maps using leaflet

leaflet(width=600, height=350)    %>%
  addTiles() %>%  # Add default OpenStreetMap map tiles
  addMarkers(lng=172.4758827, lat=-43.6402388, popup="Workshop venue")

plotly R package

plotly() for base graphics

plot_ly(economics, x = ~date, y = ~unemploy / pop,
        type="scatter", mode="markers")

ggplotly() wrapper for ggplot2 graphics

ggplotly(ggplot(data=dset, aes(x=Count, y=cutSite, colour=method)) +
  geom_point()                                                     +
  geom_smooth(method="lm")                                         +
  labs(x="Read counts", y="# Restriction sites"))

rbokeh

rbokeh example #1

source("examples/01_rbokeh.R")

http://hafen.github.io/rbokeh/index.html#preview

rbokeh example #2

Using broom package to collate model fits

source("example/02_rbokeh.R")

Shiny Package

Deployment on a Shiny server

Shiny scalability

Potential scalability issues

Certainly with the open source shiny server

The Shiny pro version scales applications across multiple processes

Streaming data

  • Maintain large amounts of data server side
  • Use data.table::fread() for large datasets
    order of magnitude faster than read.table()

Shiny example

Shiny file structure

Shiny files

  • ui.R - defines user interface
  • server.R - defines server functions, what to do when user interface changes
  • global.R - defines globals available to ui.R, server.R (optional)
  • DESCRIPTION - key value pairs in showcase mode (optional)
  • README.md - Documentation!
  • www - directory for images, css, js (optional)

Version 0.10.2, Shiny supports single-file applications

\(\mbox{ui.R} + \mbox{server.R} = \mbox{app.R}\)

Shiny application example

In app.R file

library(shiny)
ui <- fluidPage(                       ## Define the interface
  numericInput(inputId = "bins" ,
               "Number of bins", value = 25),
  plotOutput(outputId = "hist")
)
server <- function(input, output) {    ## How server reacts to interface changes
  output$hist <- renderPlot({
  set.seed(42)
  validate(need(input$bins>1, "1 or more bins required"))
    hist(rnorm(1000), breaks=seq(-6, 6, length=input$bins+1))
    })
}

shinyApp(ui = ui, server = server)     ## Create a shiny app object

Execution

shiny::runApp("examples/01_shiny", display.mode="showcase")

Shiny developer resources

Shiny uses reactive programming

Reactivity

sources = inputs, conductors = intermediate components, endpoints = outputs

                                

Simplest example: When input$obs changes, output$distPlot is notified that it needs to re-execute

server <- function(input, output) {    ## How server reacts to interface changes
  output$hist <- renderPlot({
  validate(need(input$bins>1, "1 or more bins required"))
    hist(rnorm(1000), breaks=seq(-5, 5, length=input$bins+1))
    })
}

https://shiny.rstudio.com/articles/reactivity-overview.html

Reactive elements

Reactive conductors can reuse (cache) computation
required by multiple reactive endpoints

    

Reactive flow diagram http://shiny.rstudio.com/tutorial

shiny::runApp("examples/02_shiny", display.mode="showcase")

Github shiny examples

Over 100 simple examples at https://github.com/rstudio/shiny-examples

## ssh
git clone git@github.com:rstudio/shiny-examples.git
## https
git clone https://github.com/rstudio/shiny-examples.git

In R

## shiny-examples working directory
setwd("[PATH_TO]/shiny-examples")

## Run an example
shiny::runApp('003-reactivity')

This is a good demonstration repository to test and modify shiny examples

Debugging shiny apps

  • Know your computing environment use sessionInfo()
  • Avoid installing local .libPath() libraries
  • Use shiny server logs for server deployment
  • Shiny server not required to develop applications

Development client side is faster

  • Write to STDOUT using cat(), print()
  • Add a browser() or break points using RStudio
  • Print user interface ui.R HTML to STDOUT
  • Print HTML form variables

https://shiny.rstudio.com/articles/debugging.html

options(shiny.reactlog=TRUE)
shiny::showReactLog()

Shiny template + testing suite

Shiny + (leaflet or plotly or rbokeh)

Customizing Dynamic Graphics

Rasterizing large amounts of data, Datashader graphics pipeline system

https://github.com/bokeh/datashader

Datashader decouples data processing from visualization
→ can rasterize millions of datapoints into images.

  

 
If interactive graphics need to be tailored specific questions, and you want fine control probably have to use d3.js

Session information

## R version 3.3.3 (2017-03-06)
## Platform: x86_64-apple-darwin13.4.0 (64-bit)
## Running under: OS X Yosemite 10.10.5
## 
## locale:
## [1] en_NZ.UTF-8/en_NZ.UTF-8/en_NZ.UTF-8/C/en_NZ.UTF-8/en_NZ.UTF-8
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] broom_0.4.2    rbokeh_0.5.0   dplyr_0.5.0    plotly_4.6.0  
## [5] ggthemes_3.4.0 ggplot2_2.2.1  magrittr_1.5   leaflet_1.1.0 
## 
## loaded via a namespace (and not attached):
##  [1] Rcpp_0.12.10      pryr_0.1.2        plyr_1.8.4       
##  [4] tools_3.3.3       digest_0.6.12     nlme_3.1-131     
##  [7] lattice_0.20-34   jsonlite_1.4      evaluate_0.10    
## [10] tibble_1.3.0      gtable_0.2.0      viridisLite_0.2.0
## [13] psych_1.7.3.21    shiny_0.13.2      DBI_0.4-1        
## [16] crosstalk_1.0.0   parallel_3.3.3    yaml_2.1.14      
## [19] hexbin_1.27.1     stringr_1.2.0     httr_1.2.1       
## [22] knitr_1.15.1      maps_3.1.1        htmlwidgets_0.8  
## [25] rprojroot_1.2     grid_3.3.3        R6_2.2.1         
## [28] foreign_0.8-67    rmarkdown_1.4     reshape2_1.4.2   
## [31] gistr_0.4.0       purrr_0.2.2.2     tidyr_0.6.2      
## [34] codetools_0.2-15  backports_1.0.5   scales_0.4.1     
## [37] htmltools_0.3.5   mnormt_1.5-5      assertthat_0.2.0 
## [40] mime_0.5          xtable_1.8-2      colorspace_1.3-2 
## [43] httpuv_1.3.3      labeling_0.3      stringi_1.1.2    
## [46] lazyeval_0.2.0    munsell_0.4.3